#include "MultThreadDown.h"

MultThreadDown::MultThreadDown(void)
{
	m_nThreadCount = 0 ;
	m_nCurrent = 0 ;
	m_pThread = NULL;
}

MultThreadDown::~MultThreadDown(void)
{
	KillThreads();
}

VOID MultThreadDown::SetThreads(int nCount  )
{
	if(m_pThread!=NULL)  KillThreads();
	m_nThreadCount = nCount;
	m_pThread = new CThread[ nCount ];
	m_pHttpDown = new CHttpDown[ nCount ];
	//m_pHttpUrl = new CHttpUrl[nCount];
}

VOID MultThreadDown::KillThreads()
{
	if (m_pThread)
	{
		delete[] m_pThread;
	}
	if (m_pHttpDown)
	{
		delete[] m_pHttpDown;
	}
	//if (m_pHttpUrl)
	//{
	//	delete m_pHttpUrl;
	//}
}


VOID MultThreadDown::SetDownUrl( CHttpUrl* url )
{
	m_pHttpUrl = url;
}

VOID MultThreadDown::ActiveThread()
{
	int i = 0 ; TaskStatus_t status;
	do 
	{
		for ( i = 0 ; i < m_nThreadCount ; i++)
		{
			status = m_pHttpDown[i].Status();
			if (( status == TaskStatusCompleted ) || ( status == TaskStatusNotSubmitted))
			{
				m_nCurrent = i ;
				return;
			}
		}
		Sleep(500);
	} while ( i == m_nThreadCount);
}

VOID MultThreadDown::ImagesDown()
{
	ActiveThread();
	int i = m_nCurrent; 
	LPTSTR szPath = (LPTSTR)m_tools->GetSubPathFileName();
	m_pHttpDown[i].SetUrl( m_pHttpUrl->m_url.c_str());
	m_pHttpDown[i].SetLocationFile( m_pHttpUrl->GetFileName(szPath).c_str());
	m_pThread[i].Event( &m_pHttpDown[i]);

	//m_pHttpDown[i].SetUrl( m_pHttpUrl[i].m_url.c_str());
	//m_pHttpDown[i].SetLocationFile( m_pHttpUrl[i].GetFileName(m_szPath).c_str());
	//m_pThread[i].Event( &m_pHttpDown[i]);
	//while( pDown->Status() != TaskStatusCompleted ) Sleep(500);
	//delete pDown;
}

VOID MultThreadDown::ImageDown(CHttpUrl* httpurl )
{
	LPCTSTR szpath = m_tools->GetSubPathFileName();
	CThread* thread = new CThread;
	CHttpDown* pDown = new CHttpDown;
	pDown->SetUrl( httpurl->m_url.c_str() );
	pDown->SetLocationFile( (httpurl->GetFileName(szpath)).c_str());
	thread->Event( pDown );
	while( pDown->Status() != TaskStatusCompleted ) Sleep(500);
	delete pDown;
}
